package com.firefly.app.cordova.plugins;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import net.sourceforge.simcpux.WXPayUtil;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;

import android.app.Activity;
import android.content.Intent;

import com.alibaba.fastjson.JSON;
import com.firefly.app.biz.alipay.AlipayOrderInfo;
import com.firefly.app.biz.alipay.PayDemoUtil;
import com.firefly.app.biz.wechat.WechatService;
import com.firefly.app.biz.wechat.WechatServiceImpl;
import com.firefly.app.cordova.dto.SytPayResult;
import com.firefly.app.cordova.dto.WechatDto;
import com.firefly.mobile.app.config.PackConfig;
import com.firefly.mobile.app.util.SytLog;

public class PayPackPlugin  extends CordovaPlugin implements CordovaInterface{
	private final ExecutorService threadPool = Executors.newCachedThreadPool(); 
	
	WechatService wechatService = new WechatServiceImpl();
	    /** 
	     * 注意 构造方法不能为 
	     *  
	     * Plugin_intent(){} 
	     *  
	     * 可以不写或者 定义为如下 
	     *  
	     */  
	    public PayPackPlugin() {
	    }  
	  
	  
	    @Override  
	    public boolean execute(final String action,final  org.json.JSONArray args,  
	    		final  CallbackContext callbackContext) throws org.json.JSONException {  
	        SytLog.i("packPlugin", action);  
	        cordova.getThreadPool().execute(new Runnable() {
	            public void run() {
	                try {
						execPlugin(action, args, callbackContext);
					} catch (Exception e) {
						e.printStackTrace();
						SytLog.e("packPlugin", "插件调用出错");
						callbackContext.error("插件调用出错");
					}
	            }
	        });
	        
	        return true;  
	  
	    }  
	    
	    private void execPlugin(String action, org.json.JSONArray args,  
	            CallbackContext callbackContext) throws org.json.JSONException {
	    	
	    	 if (action.equals("getCardKind"))  {
		        	 String transId = args.getString(0);
		        	 List<PackConfig> configList = PackConfig.getPayBizPacks(transId);
		        	 
		        	 if (configList == null) {
		 	    		SytLog.e("PayPackPlugin","此交易类型有误，卡类型为空，交易类型："+ transId);
		 				return;
		 			}
		        	 String json = com.alibaba.fastjson.JSONObject.toJSONString(convertPackConfig(configList));
		        	 SytLog.i("PayPackPlugin","卡类型："+ json);
		        	 callbackContext.success(json);
		        	 return;
				}else if (action.equals("alipay"))  {
					// 获取JS传递的args的第一个参数  
					String bizInfo = args.getString(0);
					AlipayOrderInfo alipayOrderInfo = JSON.parseObject(bizInfo, AlipayOrderInfo.class);
					
					SytPayResult sytPayResult = PayDemoUtil.pay(alipayOrderInfo, this.getActivity());
					String json = com.alibaba.fastjson.JSONObject.toJSONString(sytPayResult);
					SytLog.i("PayPackPlugin","支付宝支付返回前端："+ json);
					callbackContext.success(json);
		        	return;
				}else if (action.equals("wechat"))  {
					
					// 获取JS传递的args的第一个参数  
					String bizInfo = args.getString(0);
					AlipayOrderInfo alipayOrderInfo = JSON.parseObject(bizInfo, AlipayOrderInfo.class);
					
					String prePayResult =  wechatService.preWechatOrder(alipayOrderInfo.getOutTradeNo(), "", alipayOrderInfo.getTotalFee());
					SytLog.i("微信预支付返回："+prePayResult);
					WechatDto reDto = 	JSON.parseObject(prePayResult, WechatDto.class);
//					WechatDtoRes wechatDtoRes = 	JSON.parseObject(reDto.getTxt(), WechatDtoRes.class);
					SytPayResult sytPayResult = WXPayUtil.pay(reDto.getTxt());
					String json = com.alibaba.fastjson.JSONObject.toJSONString(sytPayResult);
					SytLog.i("PayPackPlugin","微信支付返回前端："+ json);
					callbackContext.success(json);
		        	return;
//					callbackContext.success(prePayResult);
				}
	    	
	    }

	    
	    private List<CardKindInfo> convertPackConfig(List<PackConfig> configList){
	    	List<CardKindInfo> cardKindInfoList = new ArrayList<PayPackPlugin.CardKindInfo>();
	    	for (PackConfig packConfig : configList) {
	    		CardKindInfo cardKindInfo = new CardKindInfo();
	    		cardKindInfo.setCardKind(packConfig.getCardKind());
	    		cardKindInfo.setEncryptTrack(packConfig.isEncryptTrack());
	    		cardKindInfo.setPayMode(packConfig.getPayMode());
	    		cardKindInfoList.add(cardKindInfo);
			}
	    	return cardKindInfoList;
	    }
	    
	    public class CardKindInfo{
	    	private String cardKind;
	    	private boolean encryptTrack;
	    	private String payMode;
			public String getCardKind() {
				return cardKind;
			}
			public void setCardKind(String cardKind) {
				this.cardKind = cardKind;
			}
			public boolean isEncryptTrack() {
				return encryptTrack;
			}
			public void setEncryptTrack(boolean encryptTrack) {
				this.encryptTrack = encryptTrack;
			}
			public String getPayMode() {
				return payMode;
			}
			public void setPayMode(String payMode) {
				this.payMode = payMode;
			}
	    	
	    }

		@Override
		public void startActivityForResult(CordovaPlugin command,
				Intent intent, int requestCode) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void setActivityResultCallback(CordovaPlugin plugin) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public Activity getActivity() {
			// TODO Auto-generated method stub
			return this.cordova.getActivity();
		}

		@Override
		public ExecutorService getThreadPool() {
			return threadPool;
		}
	    
}
